var createError = require('http-errors');
var express = require('express');
var expressWs = require('express-ws')
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const fs = require('fs');
const { initDir } = require("./src/config");
global.building = []

var indexRouter = require('./routes/index');
var dataRouter = require('./routes/data');
var uploadRouter = require('./routes/upload');
var sdkRouter = require('./routes/sdk');
var socketRouter = require('./routes/socket');
var buildRouter = require('./routes/build');
var testRouter = require('./test/router');
var app = express();
expressWs(app)

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
 // 用于解析json数据格式的中间件
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// tu文件夹也是静态资源
app.use(express.static(path.join(__dirname, 'tu')));



app.use('/', indexRouter);
app.use('/data', dataRouter);
app.use('/upload', uploadRouter)
app.use('/sdk', sdkRouter)
app.use('/socket', socketRouter);
app.use('/build', buildRouter);
app.use('/test', testRouter);



// 判断initDir列表里面的目录如果没有创建目录
initDir.forEach(item => {
  if(!fs.existsSync(item)) {
    fs.mkdirSync(item);
  }
})



// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
const port = 4567
app.listen(port, () => {console.log(`express server listen at http://localhost:${port}`)})
module.exports = app;